package com.sky.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.Dao.UserDao;
import com.sky.Service.UserService;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.properties.WeChatProperties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class UserServiceImpl
        extends ServiceImpl<UserDao, User>
        implements UserService {
    private static final String base_url = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserDao userDao;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 用户微信登陆
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) throws IOException {
        System.out.println("jsCode:" + userLoginDTO.getCode());
        System.out.println("grantType:" + weChatProperties.getGrantType());
        String openid = getOpenid(userLoginDTO);
        //判断openId是否存在，如果为空表示登陆失败，抛出业务异常
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<> ();
        queryWrapper.eq(User::getOpenid,openid);
        User user = userDao.selectOne(queryWrapper);
        //如果是新用户，则创建新用户，并返回用户信息
        if(user==null){
            //创建用户
            user = User.builder()
                    .openid(openid)
                    .build();
            //保存用户信息
            userDao.insert(user);
        }
        return user;
    }

    /**
     * 获取用户唯一标识 OpenID
     * @param userLoginDTO
     * @return
     * @throws IOException
     */
    public String getOpenid(UserLoginDTO userLoginDTO) throws IOException {
        String result = "";
        //调用微信后台 auth.code2Session 接口，换取 用户唯一标识 OpenID
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建请求对象
        String remote_url = base_url +
                "?appid=" + weChatProperties.getAppid() +
                "&secret=" + weChatProperties.getSecret() +
                "&js_code=" + userLoginDTO.getCode() +
                "&grant_type=" + weChatProperties.getGrantType();
        HttpGet httpGet = new HttpGet(remote_url);
        //发起请求，接收响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //判断响应状态
        if (response.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        //{"session_key":"BUQR2ehpR168CIWSbEeBrg==","openid":"o4Uuf7d80TjGY4zI-HgbZujAQ9Dc"}
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        //关闭资源
        response.close();
        httpClient.close();
        return openid;
    }
}
